package com.longcai.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
* @description: TODO
* @Title: HttpClientUtil
* @author 作者姓名
* @date 2019/3/20 11:38
*/
public class HttpClientUtil {

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    public static JSONObject postJson(String url, JSONObject params) {
        CloseableHttpClient client = HttpManager.httpClient();
        JSONObject res = new JSONObject();
        if (url == null) {
            res.put("status", HttpRetrunStatus.PARAMS_EX);
            return res;
        }
        log.info("HttpClientUtil-post-request-->" + url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        HttpEntity entity = new StringEntity(params.toJSONString(), Charset.forName("UTF-8"));
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                res.put("status", HttpRetrunStatus.SUCCESS);
                HttpEntity reEntity = response.getEntity();
                byte[] resp = EntityUtils.toByteArray(reEntity);
                Object parse = JSONObject.parse(resp, Feature.UseBigDecimal);
                log.info("HttpClientUtil-get-response-->" + url + JSONObject.toJSONString(parse));
                res.put("response", parse);
                return res;
            } else {
                res.put("status", HttpRetrunStatus.FAIL);
                return res;
            }
        } catch (Exception e) {
            log.error("HttpClientUtil-->" + url, e);
            res.put("status", HttpRetrunStatus.CONN_EX);
            return res;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("http-close-", e);
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("http-close-", e);
                }
            }
        }
    }

    public static JSONObject get(String url) {
        CloseableHttpClient client = HttpManager.httpClient();
        JSONObject res = new JSONObject();
        if (url == null) {
            res.put("status", HttpRetrunStatus.PARAMS_EX);
            return res;
        }
        log.info("HttpClientUtil-post-request-->" + url);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                res.put("status", HttpRetrunStatus.SUCCESS);
                HttpEntity reEntity = response.getEntity();
                byte[] resp = EntityUtils.toByteArray(reEntity);
                Object parse = JSONObject.parse(resp, Feature.UseBigDecimal);
                log.info("HttpClientUtil-get-response-->" + url + JSONObject.toJSONString(parse));
                res.put("response", parse);
                return res;
            } else {
                res.put("status", HttpRetrunStatus.FAIL);
                return res;
            }
        } catch (Exception e) {
            log.error("HttpClientUtil-->" + url, e);
            res.put("status", HttpRetrunStatus.CONN_EX);
            return res;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("http-close-", e);
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("http-close-", e);
                }
            }
        }
    }

    /**
     * 返回为jsonobject
     *
     * @param url
     * @param params
     * @return
     */
    public static JSONObject post(String url, Map<String, Object> params) {
        CloseableHttpClient client = HttpManager.httpClient();
        JSONObject res = new JSONObject();
        try {
            if (url == null) {
                res.put("status", HttpRetrunStatus.PARAMS_EX);
                return res;
            }
            UrlEncodedFormEntity entity = convertParams(params);
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = null;
            response = client.execute(httpPost);
            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                res.put("status", HttpRetrunStatus.SUCCESS);
                HttpEntity reEntity = response.getEntity();
                byte[] resp = EntityUtils.toByteArray(reEntity);
                Object parse = JSONObject.parse(resp, Feature.UseBigDecimal);


                res.put("response", parse);
                return res;
            } else {
                res.put("status", HttpRetrunStatus.FAIL);
                return res;
            }
        } catch (Exception e) {
            log.error("HttpClientUtil-->" + url + "|||" + JSONObject.toJSONString(params), e, null);
            res.put("status", HttpRetrunStatus.CONN_EX);
            return res;
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("http-close-", e, null);
                }
            }
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static UrlEncodedFormEntity convertParams(Map params) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if (params == null) {
            return null;
        }
        Set<Entry<String, Serializable>> entrySet = params.entrySet();
        for (Entry<String, Serializable> entry : entrySet) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        return entity;
    }

    public static boolean isSuccess(JSONObject res) {
        HttpRetrunStatus status = res.getObject("status", HttpRetrunStatus.class);
        if (status == null) {
            return false;
        }
        return status == HttpRetrunStatus.SUCCESS;
    }

    public static Object getResponse(JSONObject res) {
        return res.get("response");
    }

    public enum HttpRetrunStatus {
        PARAMS_EX, CONN_EX, SUCCESS, FAIL
    }
}
